package com.atguigu.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.cart.feign.ProductFeignService;
import com.atguigu.cart.interceptor.CartInterceptor;
import com.atguigu.cart.service.CartService;
import com.atguigu.cart.to.UserInfoTo;
import com.atguigu.cart.vo.Cart;
import com.atguigu.cart.vo.CartItem;
import com.atguigu.cart.vo.SkuInfoVo;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.atguigu.common.constants.CartConstant.CART_PREFIX;


@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOpts = getCartOpts();
        String item = (String) cartOpts.get(skuId.toString());

        //若购物车里已存在此商品则是一个数量的叠加,否则在redis中插入购物车数据
        if (StringUtils.isEmpty(item)){
            //如果redis中没有购物项数据
            //两个远程查询，这里使用多线程异步编程来提高效率和吞吐量
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {
                //根据skuId，远程查询sku详情
                R r = productFeignService.getSkuInfo(skuId);
                if (r.getCode() == 0) {
                    SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    if (skuInfo != null) {
                        cartItem.setSkuId(skuId);
                        cartItem.setCount(num);
                        cartItem.setCheck(true);
                        cartItem.setDefaultImg(skuInfo.getSkuDefaultImg());
                        cartItem.setPrice(skuInfo.getPrice());
                        cartItem.setTitle(skuInfo.getSkuTitle());
                    }
                }
            }, executor);

            CompletableFuture<Void> completableFuture2 = CompletableFuture.runAsync(() -> {
                //远程查询, 根据skuId查询销售属性值组合
                List<String> skuSaleAttrAsString = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrAsString);
            }, executor);

            //等待所有的异步任务完成
            CompletableFuture.allOf(completableFuture1, completableFuture2).get();
            //将购物车里面的所有商品存到redis中使用hash结构
            String json = JSON.toJSONString(cartItem);
            cartOpts.put(skuId.toString(), json);

            return cartItem;
        } else {
            //购物车中有此商品数据，则值需要数量的增加
            CartItem cartItem = JSON.parseObject(item, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            String json = JSON.toJSONString(cartItem);
            cartOpts.put(skuId.toString(), json);
            return cartItem;
        }



    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOpts = getCartOpts();
        String json = (String) cartOpts.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(json, CartItem.class);

        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {

        Cart cart = new Cart();
        //判断是临时购物车还是用户的购物车(通过是否登录来判断)
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //判断是否登录
        if (userInfoTo.getUserId()!=null) {
            //登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //如果是登录状态，并且临时购物车没有被清空
            //就把临时购物车所有数据合并到用户的购物车并清空临时购物车
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(tempCartKey);
            if (cartItems!=null && cartItems.size()>0) {
                for (CartItem cartItem : cartItems) {
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }

                //清空临时购物车数据
                clearCartInfo(tempCartKey);
            }

            //3、获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
            List<CartItem> cartItemList = getCartItems(cartKey);
            cart.setCartItems(cartItemList);

        } else {
            //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车所有购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setCartItems(cartItems);
        }


        return cart;
    }

    @Override
    public void checkItem(Long skuId, Integer checked) {
        //查看购物车的商品
        CartItem cartItem = getCartItem(skuId);
        //修改选中状态
        cartItem.setCheck(checked==1);

        String json = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOpts = getCartOpts();
        cartOpts.put(skuId.toString(), json);
    }


    @Override
    public void countItem(Long skuId, Integer num) {

        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String json = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOpts = getCartOpts();
        cartOpts.put(skuId.toString(), json);

    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOpts = getCartOpts();
        cartOpts.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //判断是否登录
        if (userInfoTo.getUserId()==null) {
            //未登录
            return null;
        } else {
            //已经登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);

            List<CartItem> collect = cartItems.stream()
                    .filter(CartItem::getCheck)//必须是选中状态
                    .map(item -> {
                        //远程查询商品的实时价格(必须是最新的价格)
                        BigDecimal price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(price);
                        return item;
                    }).collect(Collectors.toList());
            return collect;
        }

    }

    private void clearCartInfo(String tempCartKey) {
        stringRedisTemplate.delete(tempCartKey);
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> cartItems = hashOps.values();
        if (cartItems!=null && cartItems.size()>0) {
            return cartItems.stream()
                    .map(cartItem->{
                        String json = (String) cartItem;
                        return JSON.parseObject(json, CartItem.class);
                    })
                    .collect(Collectors.toList());
        }
        return null;
    }

    private BoundHashOperations<String, Object, Object> getCartOpts() {
        //添加购物车要判断是存到离线购物车还是用户的购物车
        //这里可以判断是否登录成功, 成功则是用户的购物车，否则则是离线购物车
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //登录了
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            //未登录
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> boundHashOperations = stringRedisTemplate.boundHashOps(cartKey);
        return boundHashOperations;
    }
}
